<template>
  <div class="app-container">
    <!-- 化验管理 -->
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
        <el-form-item label="化验单号" prop="code">
          <el-input
            v-noSpace
            v-model="queryParams.code"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleSeach"
            placeholder="请输入化验单号"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="productName">
          <el-select
            v-model="queryParams.productName"
            placeholder="请选择物料名称"
            clearable
            class="!w-[192px]"
            filterable
            @change="changeProducts"
          >
            <el-option
              v-for="item in optionList"
              :key="item.value"
              :label="item.label"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检验状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            @change="handleSeach"
            class="!w-[192px]"
          >
            <el-option
              v-for="item in statesList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSeach">搜索</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
          <el-button
            icon="Plus"
            type="success"
            @click="handleAdd({}, 'add')"
            v-hasPerm="'sys:rawLaboratoryManagement:edit'"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
      <el-card shadow="never">
        <el-table
          v-loading="loading"
          show-overflow-tooltip
          :tooltip-formatter="tableRowFormatter"
          :data="tableData"
        >
          <el-table-column prop="code" label="化验单号" />
          <el-table-column prop="parentCode" label="批号/编号" />
          <el-table-column prop="productName" label="物料名称" />
          <el-table-column prop="category" label="规格" />
          <el-table-column prop="reportTime" label="化验时间" />

          <el-table-column prop="purchaseQty" label="到货数量">
            <template #default="scope">
              <div>
                {{ scope.row.purchaseQty }}
                {{ unitFormat(scope.row.unit) }}
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="inspectQty" label="抽检数量" /> -->

          <el-table-column prop="conclusion" label="检验结论">
            <template #default="scope">
              <div>{{ scope.row.conclusion == 1 ? "合格" : "不合格" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="检验状态">
            <template #default="scope">
              <div>{{ stateFormatter(scope.row.status) }}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="inspector" label="检验员" /> -->
          <!-- <el-table-column prop="basis" label="检验依据" />
          <el-table-column prop="productionUnit" label="生产单位" />
          <el-table-column prop="process" label="工序" />
          <el-table-column prop="planDate" label="生产日期" />
          <el-table-column prop="checker" label="复核员" /> -->

          <!-- <el-table-column prop="conclusion" label="化验状态">
            <template #default="scope">
              <el-tag :type="scope.row.conclusion === 1 ? 'success' : 'warning'">
                {{ conclusionFormat(scope.row.conclusion) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="化验日期" />
          <el-table-column prop="remark" label="备注" /> -->

          <el-table-column label="操作" width="280">
            <template #default="scope">
              <el-button size="small" link type="primary" @click.stop="handleInfo(scope.row)">
                查看
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click.stop="handleAdd(scope.row, 'edit')"
                v-hasPerm="'sys:rawLaboratoryManagement:edit'"
              >
                修改
              </el-button>
              <!-- <el-button
                size="small"
                type="danger"
                @click.stop="handleDelete(scope.row, scope.$index)"
              >
                删除
              </el-button> -->
              <el-button
                size="small"
                link
                type="primary"
                @click.stop="handleInfo(scope.row)"
                v-hasPerm="'sys:rawLaboratoryManagement:print'"
              >
                打印
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleSeach"
        />
      </el-card>
      <el-dialog
        v-model="dialogVisible.visible"
        :title="dialogVisible.title"
        class="printDialog"
        width="1000px"
        @close="handleClose"
      >
        <!-- <div class="text-align-center text-lg">检验结果通知单(产品)</div>
        <div class="text-align-right">NO.YDBSA-D-PGB-049</div> -->
        <!-- 表格主体 -->
        <div class="border">
          <!-- 顶部信息区 -->
          <div class="grid grid-cols-3">
            <div class="flex items-center border-b border-r p-2">
              <span class="font-medium">检验类型：</span>
              <el-select
                v-model="dialogFormData.type"
                placeholder="请选择检验类型"
                class="flex-1"
                filterable
                @change="typeListChange"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <div class="flex items-center border-r border-b p-2">
              <span class="font-medium">批号/编号：</span>
              <el-select
                v-model="dialogFormData.parentCode"
                placeholder="请选择采购单号"
                class="flex-1"
                @change="changeCode"
                filterable
              >
                <el-option
                  v-for="item in purchasList"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </div>
            <div class="flex items-center border-b p-2">
              <span class="font-medium">物料名称：</span>
              <el-select
                class="flex-1"
                v-model="dialogFormData.productName"
                placeholder="请选择物料名称"
                clearable
                filterable
                @change="changeProduct"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </div>
          </div>

          <div class="grid grid-cols-3">
            <div class="flex items-center border-b border-r p-2">
              <span class="font-medium">规格：</span>
              <el-input v-noSpace v-model="dialogFormData.category" class="flex-1 !rounded-none" />
              <!-- <span>{{ dialogFormData.category }}</span> -->
            </div>

            <div class="flex items-center border-b border-r p-2">
              <span class="font-medium">到货数量（{{ unitValue?.label }}）：</span>
              <!-- <span>{{ dialogFormData.qty }}</span> -->
              <el-input
                v-noSpace
                v-model="dialogFormData.purchaseQty"
                class="flex-1 !rounded-none"
              />
            </div>

            <div class="flex items-center border-b p-2">
              <span class="font-medium">抽检数量（{{ unitValue?.label }}）：</span>
              <!-- <span>{{ dialogFormData.inspectQty }}</span> -->
              <el-input
                v-noSpace
                v-model="dialogFormData.inspectQty"
                class="flex-1 !rounded-none"
              />
            </div>
          </div>

          <div class="grid grid-cols-3">
            <div class="flex items-center border-b border-r p-2">
              <span class="font-medium">供应商：</span>
              <span>{{ dialogFormData.companyName }}</span>
              <!-- <el-input v-noSpace v-model="dialogFormData.companyName" class="flex-1 !rounded-none" /> -->
            </div>

            <div class="flex items-center border-b border-r p-2">
              <span class="font-medium">到货日期：</span>
              <!-- <span>{{ dialogFormData.planDate }}</span> -->
              <el-date-picker
                v-model="dialogFormData.reportTime"
                type="date"
                class="flex-1"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                clearable
              />
              <!-- <el-input v-noSpace v-model="dialogFormData.planDate" class="flex-1 !rounded-none" /> -->
            </div>
            <div class="flex items-center border-b p-2">
              <span class="font-medium">检验依据：</span>
              <el-input v-noSpace v-model="dialogFormData.basis" class="flex-1 !rounded-none" />
            </div>
          </div>
          <div class="grid grid-cols-3">
            <div class="flex items-center border-b p-2">
              <span class="font-medium">样品种类：</span>
              <el-select
                v-model="dialogFormData.sampleName"
                placeholder="样品种类"
                class="flex-1"
                @change="reportListChange"
                filterable
              >
                <el-option
                  v-for="item in InspectionItemList"
                  :key="item.code"
                  :label="item.sampleName"
                  :value="item.sampleName"
                />
              </el-select>
            </div>
            <div class="flex items-center border-b p-2">
              <!-- <span class="font-medium">执行标准：</span>
              <el-input v-noSpace v-model="dialogFormData.standard" class="flex-1 !rounded-none" /> -->
            </div>

            <div class="flex items-center border-b p-2"></div>
          </div>

          <!-- 检验情况表头 -->
          <div class="border-b p-2 flex justify-between font-medium">
            <div></div>
            <div>检验情况</div>
            <div></div>
            <!-- <el-button @click="addinspect">新增一行</el-button> -->
          </div>

          <!-- 检验表格头部 -->
          <div class="grid grid-cols-[80px_1fr_1fr_1fr_1fr_80px] border-b">
            <div class="border-r p-2 text-center font-medium">序号</div>
            <div class="border-r p-2 text-center font-medium">检验项目</div>
            <div class="border-r p-2 text-center font-medium">检验要求</div>
            <div class="border-r p-2 text-center font-medium">检验结果</div>
            <div class="border-r p-2 text-center font-medium">结果判定</div>
            <div class="p-2 text-center font-medium">操作</div>
          </div>

          <!-- 检验表格内容 -->
          <div
            v-for="(item, index) in dialogFormData.itemCodeList"
            :key="index"
            class="grid grid-cols-[80px_1fr_1fr_1fr_1fr_80px] border-b"
          >
            <div class="border-r p-2 flex-center">{{ index + 1 }}</div>
            <div class="border-r p-2 flex-center">
              {{ item.name }}
              <!-- <el-select
                v-model="item.qcItemCode"
                @change="InspectChange(item, index)"
                placeholder="请选择检验项目"
                class="flex-1"
                filterable
              >
                <el-option
                  v-for="item in InspectionItemList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select> -->
            </div>
            <div class="border-r flex-center p-2">{{ item.refValue }}</div>
            <div class="border-r flex-center p-2">
              <div v-if="item.refType == 'input'">
                <el-input v-noSpace v-model="item.qcValue" class="flex-1 !rounded-none" />
              </div>
              <div v-if="item.refType == 'check'">
                <el-radio-group v-model="item.qcValue">
                  <el-radio value="阴性">阴性</el-radio>
                  <el-radio value="阳性">阳性</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="border-r flex-center p-2">
              <el-radio-group v-model="item.qcResult">
                <el-radio value="1">合格</el-radio>
                <el-radio value="2">不合格</el-radio>
              </el-radio-group>
            </div>
            <div class="p-2">
              <el-button @click="delinspect(index)" text>删除</el-button>
            </div>
          </div>

          <!-- 检验结论 -->
          <div class="grid border-b grid-cols-3">
            <div class="border-r flex p-4">
              <span class="mr-2">检验结论：</span>
              <el-radio-group v-model="dialogFormData.conclusion">
                <el-radio value="1">合格</el-radio>
                <el-radio value="2">不合格</el-radio>
              </el-radio-group>
            </div>
            <div class="p-4 flex">
              <span class="mr-2">检验状态：</span>
              <el-select
                v-model="dialogFormData.status"
                placeholder="请选择状态"
                style="width: 192px"
              >
                <el-option
                  v-for="item in statesList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>

          <!-- 签名区域 -->
          <div class="grid border-b grid-cols-3">
            <div class="border-r flex-items-center flex p-4">
              <span class="mr-2">检验员：</span>
              <el-input
                v-noSpace
                v-model="dialogFormData.reportName"
                class="w-32 flex-1 !rounded-none"
              />
            </div>
            <div class="p-4 flex-items-center flex">
              <span class="mr-2">复核员：</span>
              <el-input
                v-noSpace
                v-model="dialogFormData.reviewName"
                class="w-32 flex-1 !rounded-none"
              />
            </div>
            <!-- <div class="p-4 flex-items-center flex">
              <span class="mr-2">批准：</span>
              <el-input v-noSpace v-model="dialogFormData.ratify" class="w-32 flex-1 !rounded-none" />
            </div> -->
          </div>
          <div class="flex-items-center flex p-4">
            <span class="mr-4">备注：</span>
            <el-input
              v-noSpace
              v-model="dialogFormData.remark"
              type="textarea"
              :rows="4"
              maxlength="500"
              class="w-32 flex-1 !rounded-none"
            />
          </div>
        </div>

        <template #footer>
          <span class="dialog-footer df">
            <el-button
              v-if="dialogVisible.title !== '查看' ? true : false"
              v-debounce="handleSave"
              type="primary"
            >
              确 定
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 打印预览弹窗 -->
      <!-- 打印预览对话框 -->
      <el-dialog
        class="printDialog"
        @close="handleClose"
        v-model="printDialogVisible"
        title="打印预览"
        width="60%"
      >
        <!--  -->
        <div id="myTable" class="print-preview bg-white p-2">
          <div class="text-align-center text-lg pt-[10px]">检验结果通知单(来料)</div>
          <div class="text-align-right">NO.YDBSA-D-PGB-{{ dialogFormData.code }}</div>
          <!-- 表格主体 -->
          <div class="border">
            <!-- 顶部信息区 -->
            <div class="grid grid-cols-3">
              <div class="flex border-r border-b">
                <span class="font-medium w-[120px] border-r p-2">物料名称</span>
                <div class="p-2">
                  {{ dialogFormData.productName }}
                </div>
              </div>

              <div class="flex border-r border-b">
                <span class="font-medium w-[120px] border-r p-2">规格</span>
                <div class="p-2">
                  {{ dialogFormData.category }}
                </div>
              </div>

              <div class="flex border-b">
                <span class="font-medium w-[120px] border-r p-2">批号/编号</span>
                <div class="p-2">
                  {{ dialogFormData.parentCode }}
                </div>
              </div>
            </div>

            <div class="grid grid-cols-3">
              <div class="flex border-r border-b">
                <span class="font-medium w-[120px] border-r p-2">检验依据</span>
                <div class="p-2">
                  {{ dialogFormData.basis }}
                </div>
              </div>

              <div class="flex border-r border-b">
                <span class="font-medium w-[120px] border-r p-2">到货数量</span>
                <div class="p-2">{{ dialogFormData.purchaseQty }}{{ unitValue?.label }}</div>
              </div>

              <div class="flex border-b">
                <span class="font-medium w-[120px] border-r p-2">抽检数量</span>
                <div class="p-2">{{ dialogFormData.inspectQty }}{{ unitValue?.label }}</div>
              </div>
            </div>

            <div class="grid grid-cols-3">
              <div class="flex border-r border-b">
                <span class="font-medium w-[120px] border-r p-2">供应商</span>
                <div class="p-2">
                  {{ dialogFormData.companyName }}
                </div>
              </div>

              <div class="flex border-r border-b">
                <span class="font-medium w-[120px] border-r p-2">到货日期</span>
                <div class="p-2">
                  {{ dialogFormData.reportTime }}
                </div>
              </div>

              <div class="flex border-b">
                <span class="font-medium w-[120px] border-r p-2">检验类型</span>
                <div class="p-2">
                  {{ typeFormat(dialogFormData.type) }}
                </div>
              </div>
            </div>

            <!-- 检验情况表头 -->
            <div class="border-b p-2 text-center font-medium">检验情况</div>

            <!-- 检验表格头部 -->
            <div class="grid grid-cols-5 border-b">
              <div class="border-r p-2 text-center font-medium">序号</div>
              <div class="border-r p-2 text-center font-medium">检验项目</div>
              <div class="border-r p-2 text-center font-medium">检验要求</div>
              <div class="border-r p-2 text-center font-medium">检验结果</div>
              <div class="p-2 text-center font-medium">结果判定</div>
              <!-- <div class="p-2 text-center font-medium">备注</div> -->
            </div>

            <!-- 检验表格内容 -->
            <div
              v-for="(item, index) in dialogFormData.itemCodeList"
              :key="index"
              class="grid grid-cols-5 border-b"
            >
              <div class="border-r p-2 text-center">{{ index + 1 }}</div>
              <div class="border-r p-2">
                {{ item.name }}
              </div>
              <div class="border-r p-2">
                {{ item.refValue }}
              </div>
              <div class="border-r p-2">
                {{ item.qcValue }}
              </div>
              <div class="p-2">
                {{ item.qcResult == "1" ? "合格" : "不合格" }}
              </div>
            </div>

            <!-- 检验结论 -->
            <div class="border-b p-4">
              <span class="mr-4">检验结论：</span>
              {{ dialogFormData.conclusion == "1" ? "合格" : "不合格" }}
            </div>

            <!-- 签名区域 -->
            <div class="grid border-b grid-cols-2">
              <div class="border-r flex p-4">
                <span class="mr-2">检验员：</span>
                {{ dialogFormData.reportName }}
              </div>
              <div class="p-4 flex">
                <span class="mr-2">复核员：</span>
                {{ dialogFormData.reviewName }}
              </div>
            </div>
            <div class="flex flex-items-center p-4">
              <span class="mr-4">备注：</span>
              <span>{{ dialogFormData.remark }}</span>
              <!-- <el-input v-noSpace v-model="dialogFormData.remark" class="w-32 flex-1 !rounded-none" /> -->
            </div>
          </div>
        </div>
        <template #footer>
          <el-button
            type="primary"
            v-print="handlePrintReport"
            class="!rounded-button whitespace-nowrap"
          >
            <el-icon class="mr-1"><Printer /></el-icon>
            打印
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { tableRowFormatter } from "@/utils/index";
import { FormItemRule, UploadUserFile } from "element-plus/es";
import configApi, { ConfigType } from "@/api/config/config";
import prodOrderManageApi from "@/api/prodManage/prodOrderManage";
import laboratoryManagementAPI, {
  ProdReportInfo,
  Inspect,
  qualityPageQuery,
} from "@/api/quality/laboratoryManagement";
import PurchasApi, { PurchasPageVO, PurchasPageQuery } from "@/api/order/purchas";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { useDateRanges } from "@/utils/useDateRanges";
// 时间范围
const { getWeekRange, getMonthRange, getQuarterRange, getYearRange, getDateRange } =
  useDateRanges();

const btn = ref("1");
// 打印弹窗
const printDialogVisible = ref(false);
// 加载loading
const loading = ref(false);
// 分页总数
const total = ref(0);
// 搜索ref
const queryFormRef = ref(ElForm);

//一级弹窗
const dialogVisible = reactive({ visible: false, title: "", type: "" });
const statesList = ref([
  {
    label: "待检验",
    value: 0,
  },
  {
    label: "检验中",
    value: 1,
  },
  {
    label: "检验通过",
    value: 2,
  },
  {
    label: "检验不通过",
    value: 3,
  },
]);
function stateFormatter(states: number) {
  let state = "";
  switch (states) {
    case 1:
      state = "检验中"; // 当表达式的结果等于 value1 时，则执行该代码
      break;
    case 2:
      state = "检验通过"; // 当表达式的结果等于 value2 时，则执行该代码
      break;
    case 3:
      state = "检验不通过"; // 当表达式的结果等于 valueN 时，则执行该代码
      break;
    default:
      state = "待检验"; // 如果没有与表达式相同的值，则执行该代码
  }
  return state;
}
const queryParams: qualityPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  qualityType: 1,
});

// 类型
const typeList = ref([
  { label: "果蔬", value: 1 },
  { label: "肉类", value: 2 },
]);
const conclusionList = ref([
  { label: "已完成", value: 0 },
  { label: "待审核", value: 1 },
]);
//类型格式化
const typeFormat = (val: any) => {
  return typeList.value.find((item) => item.value == val)?.label;
};

// 列表参数
const tableData = ref([]);

const dialogFormData: ProdReportInfo = reactive({
  orderType: 1,
  qualityType: 1,
  unit: "",
  sampleName: "",
  reportTime: getDateRange(),
  itemCodeList: [],
});

let purchasList: any;

// 查询生产批次号
function getpurchas() {
  let data = {
    pageNum: 1,
    pageSize: 999,
  };
  PurchasApi.getPage(data)
    .then((data) => {
      console.log(data, "data");
      let list = data?.list.map((item: any) => {
        return {
          label: item.code,
          value: item.code,
          purchaseQty: item.totalQty,
          planDate: item.planDate,
          companyName: item.companyName, //供应商
        };
      });
      purchasList = list;
      console.log(purchasList);
    })
    .finally(() => {});
}

const delinspect = (index: any) => {
  // tableData.splice(index, 1);
  dialogFormData.itemCodeList.splice(index, 1);
};

const changeCode = (val: any) => {
  dialogFormData.purchaseQty = val.purchaseQty;
  // dialogFormData.planDate =  getDateRange();
  dialogFormData.parentCode = val.value;
  dialogFormData.companyName = val.companyName;
  console.log(dialogFormData, "dialogFormData");
  getContractList();
  // dialogFormData.process = val.label + "加工";
};
//物料名称
const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const optionList = ref<{ value: string; label: string }[]>([]); // 显式指定类型
// 产品列表
const getContractList = () => {
  PurchasApi.detailList(dialogFormData.parentCode)
    .then((data: any) => {
      options.value = (data || []).map((item: any) => ({
        value: item.productCode,
        label: item.productName,
        productType: item.productType,
        unit: item.unit,
      }));
    })
    .catch((err) => {})
    .finally(() => {});
};
const getContractLists = () => {
  configApi
    .getProductList({ pageNum: 1, pageSize: 999, productType: "2" })
    .then((data) => {
      console.log(data, "data");
      // rowTableData.value = data?.list || [];
      optionList.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
        productType: item.productType,
        category: item.packageSize,
        unit: item.unit,
      }));
    })
    .catch((error) => {
      //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
};

function changeProducts(val: any) {
  console.log(val);
  // dialogFormData.productCode = val.value;
  // dialogFormData.productName = val.label;
  queryParams.productName = val.label;
  // dialogFormData.category = val.category;
  // dialogFormData.productCategory = val.productType;
  // dialogFormData.unit = val.unit;
  // dialogFormData.process = val.label + "加工";
  // // dialogFormData.unitPrice = val.price;
  // // dialogFormData.remark = val.remark;
  // unitValue.value = unitOptions.value.find((item) => item.value === val.unit) as any;
}
function changeProduct(val: any) {
  console.log(val);
  dialogFormData.productCode = val.value;
  dialogFormData.productName = val.label;
  // dialogFormData.category = val.category;
  dialogFormData.productCategory = val.productType;
  dialogFormData.unit = val.unit;
  dialogFormData.process = val.label + "加工";
  // dialogFormData.unitPrice = val.price;
  // dialogFormData.remark = val.remark;
  unitValue.value = unitOptions.value.find((item) => item.value === val.unit) as any;
}
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 查询方法
const handleSeach = () => {
  loading.value = true;
  laboratoryManagementAPI
    .getAnalysisReport(queryParams)
    .then((data) => {
      console.log(data);
      tableData.value = [...(data?.list as never)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
// 重置方法
const handleReset = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleSeach();
};
const cleraForm = () => {
  let data = {
    id: "",
    actualQuantity: null, //实际数量
    basis: null, //检验依据
    category: "", //规格
    code: "", //质检单号
    conclusion: "", //检验结论
    inspectQty: null, //抽检数量
    itemCodeList: [],
    orderType: 1, //订单类型, 0=生产单号, 1=采购单号
    parentCode: "", //生产单号
    process: "", //工序
    productCategory: "", //产品类型
    productCode: "", //产品编号
    productName: "", //物料名称
    purchaseQty: null, //采购数量
    qualityType: 1, //质检单类型, 0=产品质检单, 1=原材料质检单
    remark: "", //备注
    reportName: "", //质检人
    reviewName: "", //复核员
    reportTime: getDateRange(), //检验日期
    planDate: "", //生产日期
    companyName: "", //生产单位
    standard: "", //执行标准
    type: null, //检验类型
    unit: "", //单位
  };

  Object.assign(dialogFormData, { ...data });
};
const handleInfo = (row: any) => {
  // selectedRow.value = row;
  printDialogVisible.value = true;
  ProdReportByData(row.code);
};
// 新增、修改、查看方法
const handleAdd = (row: any, type: any) => {
  console.log(row);
  dialogVisible.visible = true;
  dialogVisible.type = type;
  if (type === "add") {
    dialogVisible.title = "新增";
    // dialogFormData.order
    // delete dialogFormData.id;
  }
  if (type === "edit") {
    dialogVisible.title = "修改";
    ProdReportByData(row.code);
  }
  // if (type === "info") {
  //   dialogVisible.title = "查看";
  //   let data = { ...row };
  //   nextTick(() => {
  //     Object.assign(dialogFormData, { ...data });
  //   });
  // }
};
const ProdReportByData = (code: any) => {
  laboratoryManagementAPI
    .getProdReportByCode(code)
    .then((data) => {
      console.log(data, "data");
      Object.assign(dialogFormData, { ...data });
      unitValue.value = unitOptions.value.find((item) => item.value === dialogFormData.unit) as any;
      typeListChange(data.type);
      // InspectionChange({ sampleName: data.sampleName, type: data.type });
    })
    .finally(() => {
      loading.value = false;
    });
};
// 删除操作
const handleDelete = (row: any, index: any) => {
  // loading.value = true;
  // ElMessageBox.confirm("确定要删除吗?", "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  // })
  //   .then(() => {
  //     tableData.splice(index, 1);
  //     ElMessage.success("删除成功");
  //     loading.value = false;
  //     // basketManagementAPI
  //     //   .delete({ id: row.id })
  //     //   .then((data) => {
  //     //     ElMessage.success("删除成功");
  //     //     handleSeach();
  //     //   })
  //     //   .catch((error) => {
  //     //     loading.value = false;
  //     //     ElMessage.error(`error`);
  //     //   });
  //   })
  //   .catch(() => {});
};
// 弹窗关闭
const handleClose = () => {
  console.log("aaa");
  dialogVisible.visible = false;
  printDialogVisible.value = false;
  cleraForm();
  console.log(dialogFormData, "dialogFormData");

  // dialogFormRef.value?.clearValidate();
  // dialogFormRef.value?.resetFields();
};
const handlePrintReport = {
  id: "myTable", // 必填：要打印的DOM元素ID
  beforeOpenCallback: () => {
    console.log("打印窗口打开前");
  },
  closeCallback: () => {
    console.log("打印窗口关闭后");
  },
};
// const handlePrintReport = () => {
//   const table = document.getElementById("myTable") as HTMLElement;
//   html2canvas(table, {
//     scale: 3, // 关键参数
//     removeContainer: true,
//     x: 0,
//     y: 0,
//     width: table.offsetWidth,
//     height: table.offsetHeight,
//     foreignObjectRendering: false, // 对于复杂内容设为false可能更好
//   }).then((canvas) => {
//     const imgData = canvas.toDataURL("image/png");
//     const pdf = new jsPDF("p", "mm", "a4");
//     const imgWidth = 210; // A4纸的宽度
//     const pageHeight = 295; // A4纸的高度
//     const imgHeight = (canvas.height * imgWidth) / canvas.width;
//     let heightLeft = imgHeight;
//     let position = 0;

//     pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
//     heightLeft -= pageHeight;

//     while (heightLeft >= 0) {
//       position = heightLeft - imgHeight;
//       pdf.addPage();
//       pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
//       heightLeft -= pageHeight;
//     }

//     // pdf.save("table.pdf");
//     // 直接打印
//     pdf.autoPrint();
//     window.open(pdf.output("bloburl"));
//   });
// };
// 保存操作
const handleSave = () => {
  loading.value = true;
  console.log(dialogFormData, "dialogFormData");
  laboratoryManagementAPI
    .saveProdReport(dialogFormData)
    .then((data) => {
      loading.value = false;
      dialogVisible.visible = false;
      ElMessage.success("保存成功");
      handleSeach();
    })
    .catch((error) => {
      loading.value = false;
      // ElMessage.error(`error`);
    });
  // console.log(dialogFormData, "dialogFormData");
  // if (dialogVisible.type === "add") {
  //   dialogFormData.id = `HY${new Date().getTime()}`;
  //   tableData.push(JSON.parse(JSON.stringify(dialogFormData)));
  //   dialogVisible.visible = false;
  //   ElMessage.success("保存成功");
  // } else {
  //   const index = tableData.findIndex((item: any) => item.id === dialogFormData.id);
  //   if (index !== -1) {
  //     tableData.splice(index as any, 1, JSON.parse(JSON.stringify(dialogFormData)));
  //   }
  //   dialogVisible.visible = false;
  //   ElMessage.success("修改成功");
  // }
  // loading.value = true;
  // dialogFormRef.value.validate((valid: boolean) => {
  //   if (!valid) {
  //     return;
  //   }
  //   const apiCall =
  //     dialogVisible.type === "add" ? basketManagementAPI.add : basketManagementAPI.update;
  //   apiCall(dialogFormData)
  //     .then((data) => {
  //       loading.value = false;
  //       dialogVisible.visible = false;
  //       ElMessage.success("保存成功");
  //       handleSeach();
  //     })
  //     .catch((error) => {
  //       loading.value = false;
  //       ElMessage.error(`error`);
  //     });
  // });
};
let InspectionItemList: Inspect[] = reactive([]);
const reportListChange = (sampleName: any) => {
  let data = InspectionItemList.find((item) => item.sampleName == sampleName) as any;
  dialogFormData.sampleName = data.sampleName;
  InspectionChange(data);
};
const InspectionChange = (data: any) => {
  laboratoryManagementAPI
    .getLastReportBySampleName({ type: data.type, sampleName: data.sampleName })
    .then((data) => {
      console.log(data, "getLastReportBySampleName");
      let list = data.map((item: any) => {
        return {
          id: "",
          code: "",
          name: item.name,
          sampleName: item.sampleName,
          parentCode: "",
          qcItemCode: item.code,
          qcResult: "",
          qcValue: "",
          refType: item.refType,
          refValue: item.refValue,
          remark: "",
        };
      });
      if (list.length == 0) {
        dialogFormData.itemCodeList = [];
      } else {
        dialogFormData.itemCodeList = list;
      }
    })
    .catch((error) => {
      // loading.value = false;
      // ElMessage.error(`error`);
    });
};
// 类型下拉
const typeListChange = (val: any) => {
  let data = {
    sampleName: "",
    type: val,
  };
  laboratoryManagementAPI
    .getLastReportBySampleName({ type: data.type, sampleName: data.sampleName })
    .then((data) => {
      // console.log(data, "getLastReportBySampleName");
      // Object.assign(InspectionItemList, { ...data });
      InspectionItemList = { ...data };
    })
    .catch((error) => {
      // loading.value = false;
      // ElMessage.error(`error`);
    });
};

onMounted(() => {
  handleSeach();
  getUnitList();
  getpurchas();
  getContractLists();
  // getContractList();
});
</script>

<style lang="scss" scoped>
#myTable {
  color: #000000 !important;
  font-family: Arial, sans-serif !important;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-family: Arial, sans-serif;
}
.el-input :deep(.el-input__wrapper) {
  box-shadow: none;
  border: 1px solid #dcdfe6;
}
:deep(.printDialog) {
  margin: 5vh auto;
}
@media print {
  body {
    margin: 0;
    padding: 0;
  }
  .print-preview {
    width: 100%;
    height: 100%;
    box-shadow: none;
  }
  table {
    width: 100% !important;
    table-layout: auto;
  }
  @page {
    size: auto; /* auto is the initial value */
    margin: 3mm; /* this affects the margin in the printer settings */
  }
}
// #print-area {
//   position: absolute;
//   left: 0;
//   top: 10%;
//   width: 100%;
//   height: 100%;
//   margin: 0;
//   // padding: 0;
//   // position: absolute;
//   left: 50%;
//   // top: -20%;
//   transform: translateX(-50%);
//   // width: 210mm;
//   // height: 297mm;
//   // margin: 0;
//   // background: white;
//   // box-shadow: none;
//   padding: 30mm;
// }
// @media print {
//   @page {
//     margin-top: 0;
//     margin-bottom: 0;
//     marks: none; /* 隐藏裁剪标记 */
//   }
//   :deep(.printDialog) {
//     margin: 0 auto;
//     padding: 0;
//   }
//   #print-area {
//     // position: absolute;
//     // left: 50%;
//     // top: 0%;
//     // transform: translateX(-50%);
//     width: 100vw;
//     height: 100vh;
//     margin: 0;
//     background: white;
//     box-shadow: none;
//     // padding: 20mm;
//   }
// }
</style>
